<template>
  <div class="image-upload">
    <el-upload
      :class="{disable:fileList.length>0}"
      action="#"
      list-type="picture-card"
      :http-request="uploadFn"
      :on-change="changeFn"
      :file-list="fileList"
      :on-remove="onRemoveFn"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 进度条 -->
    <el-progress v-if="isShow" :text-inside="true" :stroke-width="26" :percentage="percent" />
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'

// 实例化cos对象
var cos = new COS({
  SecretId: 'AKIDFJ7eutd6JFwMVN4UdV7TZOwDDbjaAUWH',
  SecretKey: 'WljQqzrTt3xaw2rPghRt4zd05tRiiSw9'
})
export default {
  data() {
    return {
      fileList: [],
      percent: 0,
      isShow: false
    }
  },

  methods: {
    uploadFn(file) {
      console.log('uploadFn', file)
      const fileName = file.file.name.split('.')[0]

      // 调用腾讯云cos对象提供的接口实现图片上传
      cos.putObject(
        {
          Bucket: 'hr-project-73-1311279992' /* 储存桶名字 必须 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: fileName /* 上传后的文件名 自定义即可 必须 */,
          StorageClass: 'STANDARD',
          Body: file.file, // 上传文件对象
          // 当前图片上传进度 onProgress
          onProgress: (progressData) => {
            console.log('当前图片上传进度', JSON.stringify(progressData))
            // console.log(progressData);
            this.percent = progressData.percent * 100
          }
        },
        // 上传成功后，怎么拿线上地址
        (err, data) => {
          // console.log(this);
          // console.log(err || data);
          if (err) {
            return this.$message.error('图片上传失败')
          } else {
            console.log('图片上传成功的返回值', data)
            this.fileList[0].url = 'https://' + data.Location
            this.fileList[0].status = 'success'
            this.$message.success('图片上传成功')
            // this.isShow = false
            this.percent = 0
          }
        }
      )
    },
    changeFn(file) {
      console.log('changeFn', file)
      this.isShow = true
      this.fileList.push({ url: file.url, status: 'ready' })
    },

    // 移出头像
    onRemoveFn() {
      this.fileList = []
    }
  }
}
</script>

<style lang="scss">
.image-upload {
    position: relative;
display: inline-block;
  .disable {
    .el-upload--picture-card {
      display: none;
    }
  }
  .el-progress{
      width: 148px;
      position: absolute;
      top: 50px;
  }
}
</style>
